<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .active {
            background-color: pink;
        }
    </style>
</head>

<body>
    <ul id="parent">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        const parent = document.getElementById('parent')

        // 变换颜色
        function changeColor() {
            if (this.classList.contains('active')) {
                this.classList.remove('active')
            } else {
                this.classList.add('active')
            }
        }

        function matchSelector(target, selector) {
            if (selector.startsWith('#')) { //id
                return target.id === selector.slice(1)
            }
            if (selector.startsWith('.')) {
                return target.classList.contains(selector.slice(1)) //类名
            }
            return target.nodeName.toLowerCase() === selector //标签
        }

        function delegate(parent, selector, type, handle) {
            if (parent.addEventListener) {
                parent.addEventListener(type, eventFn, false)
            } else {
                parent.attachEvent('on' + type, handle) //兼容
            }
            function eventFn(e) {
                const event = e || window.event
                const target = event.target
                if (matchSelector(target, selector)) {
                    handle?.call(target, e)
                }
            }
        }

        delegate(parent, 'li', 'click', changeColor)

    </script>
</body>

</html>